package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;


import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加延迟任务
     *
     * @param task 任务对象
     * @return
     */
    @Override
    public long addTask(Task task) {
        //1.先把数据加到数据库,如果没有问题再加载到redis
        Boolean flag = addTaskToDb(task);
        if (flag) {
            //2.加载到redis数据库
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        Boolean falg = false;
        //1.更新数据库,修改状态,删除info表
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        if (null != task) {
            //删除redis的数据
            Boolean aBoolean = removeTaskFromCache(task);//因为取消redis需要task中的数据,所以前面返回值是task
            falg = aBoolean;
        }
        return falg;
    }

    /**
     * 拉取任务,将list中的任务进行拉取,拉取过后,数据库中的logs中的状态改为已执行状态
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type + "_" + priority;
        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        Task task = null;
        try {
            if (StringUtils.isNotEmpty(json)) {
                task = JSON.parseObject(json, Task.class);//将redis中的jason转为task对象,再通过这个对象修改状态
                if (null != task.getTaskId()) {
                    updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return task;//因为是拉取,我们拉取下来的对象肯定要接收一下
/*        Task task=null;
        try {
            String taskStr = cacheService.lRightPop(ScheduleConstants.TOPIC + type + "_" + priority);
            if (StringUtils.isNotBlank(taskStr)){
                task= JSON.parseObject(taskStr, Task.class);
                if (null!=task.getTaskId()){
                    updateDb(task.getTaskId(), type);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }return task;*/
    }


    /**
     * 取消任务  删除redis中的数据
     *
     * @param task
     */
    private Boolean removeTaskFromCache(Task task) {
        long currentTimeMillis = System.currentTimeMillis();//当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextTime = calendar.getTimeInMillis();//未来的五分钟
        //定义key
        String key = task.getTaskType() + "_" + task.getPriority();
        //根据key值删除数据
        long count = -1;
        try {
            if (task.getExecuteTime() < currentTimeMillis) {//删除list
                count = cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
            } else if (task.getExecuteTime() < nextTime) {
                count = cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count == -1 ? false : true;
        /*Boolean flag=false;
        String topickey=ScheduleConstants.TOPIC+task.getTaskType()+"_"+task.getPriority();
        String futurekey=ScheduleConstants.FUTURE+task.getTaskType()+"_"+task.getPriority();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,5);
        long count=-1;
        long nextTime = instance.getTimeInMillis();
        if (task.getExecuteTime()<=System.currentTimeMillis()){
            count = cacheService.lRemove(topickey, 0, JSON.toJSONString(task));
        }else if (task.getExecuteTime()<nextTime){
            count = cacheService.zRemove(futurekey, JSON.toJSONString(task));
        }

        return count==-1?false:true;*/
    }

    /**
     * 取消任务  修改数据库表中的数据
     *
     * @param taskId
     * @param type
     * @return
     */
    private Task updateDb(long taskId, int type) {
        Task task = null;
        try {
            taskinfoMapper.deleteById(taskId);//删除info表
            //修改log表的状态
            TaskinfoLogs logs = taskinfoLogsMapper.selectById(taskId);
            logs.setStatus(type);
            taskinfoLogsMapper.updateById(logs);
            //拷贝属性到task
            task = new Task();
            BeanUtils.copyProperties(logs, task);
            task.setExecuteTime(logs.getExecuteTime().getTime());
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return task;
/*        Task task =null;
        try {
            taskinfoMapper.deleteById(taskId);
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectOne(Wrappers.<TaskinfoLogs>lambdaQuery()
                    .eq(TaskinfoLogs::getTaskId, taskId));
            taskinfoLogs.setStatus(type);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            //后续拉取任务要修改task的执行时间,所以要传一个Task对象,拷贝属性
            task=new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        } catch (BeansException e) {
            e.printStackTrace();
        }return task;*/
    }

    /**
     * 添加数据到Redis表,有两张表,一个list,一个Zset
     *
     * @param task
     */
    private void addTaskToCache(Task task) {
        //先比较时间
        try {
            long currentTimeMillis = System.currentTimeMillis();//当前时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, 5);
            long nextTime = calendar.getTimeInMillis();//未来的五分钟
            //定义key
            String key = task.getTaskType() + "_" + task.getPriority();
            if (task.getExecuteTime() < currentTimeMillis) {//立即发送,存list
                cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
            } else if (task.getExecuteTime() < nextTime) {
                cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());//分数就用执行的时间来排序
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*try {
            if (null!=task.getTaskId()){
                Long taskId = task.getTaskId();
                TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectOne(Wrappers.<TaskinfoLogs>lambdaQuery()
                        .eq(TaskinfoLogs::getTaskId, taskId));
                if (null!=taskinfoLogs){
                    long time = taskinfoLogs.getExecuteTime().getTime();
                    long nowtime = System.currentTimeMillis();
                    Calendar instance = Calendar.getInstance();
                    instance.add(Calendar.MINUTE,5);
                    Date nextTime = instance.getTime();
                    String topickey=ScheduleConstants.TOPIC+task.getTaskType()+"_"+task.getPriority();
                    String futurekey=ScheduleConstants.FUTURE+task.getTaskType()+"_"+task.getPriority();
                    if (time<nowtime){
                        cacheService.lLeftPush(topickey,JSON.toJSONString(task));
                    }else if (time<nextTime.getTime()){
                        cacheService.zAdd(futurekey,JSON.toJSONString(task),task.getExecuteTime());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/

    }

    /**
     * 添加数据到数据库,两张表,拷贝属性
     *
     * @param task
     * @return
     */
    private Boolean addTaskToDb(Task task) {
        Boolean flage = true;
        try {
            //1. 先到添加到taskinfo表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            //处理不能复制的属性执行时间
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));//long->Date
            //保存
            taskinfoMapper.insert(taskinfo);
            task.setTaskId(taskinfo.getTaskId());//给task的Id赋值,后面要用
            //2.再添加到taskinfoLogs表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            //处理没有copy到的值
            taskinfoLogs.setVersion(1);//初始化
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);//初始化

            taskinfoLogsMapper.insert(taskinfoLogs);
        } catch (BeansException e) {
            e.printStackTrace();
            flage = false;
        }
        return flage;
/*        Boolean flag=true;
        try {
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setStatus(0);
            taskinfoLogs.setVersion(1);
            taskinfoLogsMapper.insert(taskinfoLogs);
            task.setTaskId(taskinfo.getTaskId());
        } catch (BeansException e) {
            e.printStackTrace();
            flag=false;
        }return flag;*/
    }

    /**
     * 刷新Zset任务到list中
     */
    @Scheduled(cron = "0 */1 * * * ?")//每一分钟刷新一次
    public void refresh() {
        log.info("开始实时刷新任务");
        //先扫描所有的future*的key值
        String lock = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotEmpty(lock)) {
            String key = ScheduleConstants.FUTURE;
            Set<String> setList = cacheService.scan(key + "*");
            if (!setList.isEmpty()){
                //拼接key的后缀+topic
                for (String set : setList) {
                    String[] split = set.split(key);
                    String topickey = ScheduleConstants.TOPIC + split[1];
                    //找到topic的数据集,通过list的Range
                    Set<String> Zset = cacheService.zRangeByScore(key + split[1], 0, System.currentTimeMillis());
                    if (null != Zset && Zset.size() > 0) {
                        //使用工具类刷新
                        cacheService.refreshWithPipeline(key + split[1], topickey, Zset);
                        log.info("成功的将"+set+"刷新到了"+topickey);
                    }
                }
            }
            //释放锁
            cacheService.releaseLock("FUTURE_TASK_SYNC");
        }
        /*String lock = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        //futurekey,topickey,还有参数集合,参数从zset里面拿出来.因为是从zset中刷新到list中
        Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        if (StringUtils.isNotBlank(lock)){
            if (!futurekeys.isEmpty()){
                for (String futurekey : futurekeys) {
                    String[] split = futurekey.split(ScheduleConstants.FUTURE);
                    String topickey=ScheduleConstants.TOPIC+split[1];
                    Set<String> zset = cacheService.zRangeByScore(futurekey, 0, System.currentTimeMillis());
                    if (!zset.isEmpty()){
                        cacheService.refreshWithPipeline(futurekey,topickey,zset);
                    }
                }
            }cacheService.releaseLock("FUTURE_TASK_SYNC");
        }*/
    }

    /**
     * 数据库任务同步到redis
     */
    @PostConstruct//预热,spring运行时就先加载到redis中
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        //清理缓存数据
        clearCache();
        //查询logs表中的数据,将小于未来5分钟的数据加载到redis中
        //找出数据库中小于未来五分钟的数据,将他们转换成task对象进行到redis中
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<TaskinfoLogs> taskinfoLogsList = taskinfoLogsMapper.selectList(Wrappers.<TaskinfoLogs>lambdaQuery().lt(TaskinfoLogs::getExecuteTime, calendar.getTime()));
        if (null!=taskinfoLogsList){
            for (TaskinfoLogs taskinfoLogs : taskinfoLogsList) {
                //因为添加到redis中需要的是一个task对象,所以需要将taskinfologs拷贝成task对象传进redis中
                Task task = new Task();
                BeanUtils.copyProperties(taskinfoLogs,task);
                task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
                addTaskToCache(task);//调用添加到redis数据库的方法
            }log.info("记载数据库中的数据:"+taskinfoLogsList+"到redis中");
        }
       /* Set<String> set = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> list = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(set);
        cacheService.delete(list);
       //查找数据库中小于未来5分钟的数据
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,5);
        long nextTime = instance.getTimeInMillis();
        List<TaskinfoLogs> taskinfoLogs = taskinfoLogsMapper.selectList(Wrappers.<TaskinfoLogs>lambdaQuery().lt(TaskinfoLogs::getExecuteTime, nextTime));
        for (TaskinfoLogs taskinfoLog : taskinfoLogs) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfoLog,task);
            task.setExecuteTime(taskinfoLog.getExecuteTime().getTime());
            addTask(task);//将task对象传入方法中,这个方法就是加到redis中
        }*/

    }

    /**
     * 清空redis的缓存
     */
    private void clearCache() {
        Set<String> topic = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> future = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topic);
        cacheService.delete(future);
    }
}
